import React, { useState, useCallback } from 'react';
import { Modal, Input, Space, Typography } from 'antd';
import type { ModalProps } from 'antd';

const { Text } = Typography;

export interface DeleteConfirmProps extends Omit<ModalProps, 'onOk' | 'visible'> {
  /** 是否显示 */
  open: boolean;
  /** 标题 */
  title?: string;
  /** 内容 */
  content?: React.ReactNode;
  /** 确认回调 */
  onConfirm: () => void | Promise<void>;
  /** 取消回调 */
  onCancel: () => void;
  /** 自定义验证答案 */
  customAnswer?: string;
}

/**
 * 生成随机数学运算
 */
const generateMathProblem = () => {
  const num1 = Math.floor(Math.random() * 10) + 1;
  const num2 = Math.floor(Math.random() * 10) + 1;
  const operators = ['+', '-', '*'];
  const operator = operators[Math.floor(Math.random() * operators.length)];

  let answer: number;
  switch (operator) {
    case '+':
      answer = num1 + num2;
      break;
    case '-':
      answer = num1 - num2;
      break;
    case '*':
      answer = num1 * num2;
      break;
    default:
      answer = num1 + num2;
  }

  return {
    problem: `${num1} ${operator} ${num2} = ?`,
    answer: answer.toString(),
  };
};

const DeleteConfirm: React.FC<DeleteConfirmProps> = ({
  open,
  title = '确认删除',
  content = '删除后不可恢复，请谨慎操作。',
  onConfirm,
  onCancel,
  customAnswer,
  ...modalProps
}) => {
  // 生成数学问题
  const [mathProblem] = useState(generateMathProblem);
  const [answer, setAnswer] = useState('');
  const [error, setError] = useState(false);

  // 处理输入变化
  const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    setAnswer(e.target.value);
    setError(false);
  }, []);

  // 处理确认
  const handleOk = useCallback(async () => {
    const correctAnswer = customAnswer || mathProblem.answer;
    if (answer !== correctAnswer) {
      setError(true);
      return;
    }
    try {
      await onConfirm();
      setAnswer('');
      setError(false);
    } catch (err) {
      // 处理错误
    }
  }, [answer, mathProblem.answer, customAnswer, onConfirm]);

  // 处理取消
  const handleCancel = useCallback(() => {
    setAnswer('');
    setError(false);
    onCancel();
  }, [onCancel]);

  return (
    <Modal
      title={title}
      open={open}
      onOk={handleOk}
      onCancel={handleCancel}
      okButtonProps={{ disabled: !answer }}
      {...modalProps}
    >
      <Space direction="vertical" style={{ width: '100%' }}>
        <div>{content}</div>
        <div>
          <Text>请计算：{mathProblem.problem}</Text>
          <Input
            placeholder="请输入计算结果"
            value={answer}
            onChange={handleInputChange}
            status={error ? 'error' : ''}
          />
          {error && (
            <Text type="danger" style={{ fontSize: 12 }}>
              计算错误，请重试
            </Text>
          )}
        </div>
      </Space>
    </Modal>
  );
};

export default DeleteConfirm; 